/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package run;

import IGUI.Publisher;
import IGUI.Subscriber;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;

/**
 *
 * @author olivierm
 */
public class PublisherImpl implements Publisher, Serializable{

    protected Vector listePublishers = new Vector();
    protected Vector listePublishersSrv = new Vector();
    
    public PublisherImpl() throws RemoteException{
        super();
        UnicastRemoteObject.exportObject(this,0);
    }    
    
    public void subscribe(Subscriber obs) throws RemoteException {
        listePublishers.add(obs);
        notifyAllSubscibers();
    }

    public void subscribeSrv(Subscriber obs) throws RemoteException {
        listePublishersSrv.add(obs);
    }    
    
    public void unsubscribe(Subscriber obs) throws RemoteException {
        listePublishers.remove(obs);
        notifyAllSubscibers();
    }

    public int getNbrSubscribes() throws RemoteException {
        return listePublishers.size();
    }
    
    public void notifyAllSubscibers() throws RemoteException {

        //On prévient le serveur
        for (int i = 0; i < this.listePublishersSrv.size(); i++){
            Subscriber obsSrv = (Subscriber) this.listePublishersSrv.get(i);
                obsSrv.update(this);
            }        
        //On prévient les clients
        for (int i = 0; i < this.listePublishers.size(); i++){
            Subscriber obs = (Subscriber) this.listePublishers.get(i);
                obs.update(this.getClass().getSimpleName());
            }
            //obs.newValue(this.listePublishers.size());
    }
    
    public void unSubscribeAllSubscribers(){
        this.listePublishers.removeAllElements();
    }


}
